import React, { useEffect, useState } from 'react'
import './index.scss'
import { fetchLogin } from '@/store/modules/user.js'
import { http } from '@/utils'
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'
import { getToken } from '@/utils'
const validationStrategies = {
	mobile: [
		(value) => value.length === 11 ? null : '请输入正确的手机号',
		(value) => /^1[3-9]\d{9}/.test(value) ? null : '请输入正确的手机号'
	],
	code: [
		(value) => value.length === 6 ? null : '请输入正确的验证码'
	]
}
const validateField = (name, value) => {
	const strategies = validationStrategies[name]
	return strategies.reduce((acc, strategy) => acc || strategy(value), null)
}

const Login = () => {
	const dispatch = useDispatch()
	const navigate = useNavigate()

	const [loginInfo, setLoginInfo] = useState({
		mobile: '',
		code: ''
	})

	const [errors, setErrors] = useState({})

	const handleSubmit = (e) => {
		e.preventDefault();
		const mobileError = validateField('mobile', loginInfo.mobile)
		const codeError = validateField('code', loginInfo.code)
		setErrors({ ...errors, 'mobile': mobileError, 'code': codeError })
		if (!errors.code && !errors.mobile) {
			dispatch(fetchLogin(loginInfo))
				.then(() => {
					navigate('/')
					message.success('登录成功')
				})
				.catch(() => {
					message.error('登录失败，请检查手机号或验证码是否正确')
				})
		}
	}

	const handleInputChange = (e) => {
		const { name, value } = e.target;
		setLoginInfo({
			...loginInfo,
			[name]: value
		})
		const error = validateField(name, value)
		setErrors({ ...errors, [name]: error })
	}
	const [codeText, setCodeText] = useState('获取验证码')

	const handlerGetCode = async () => {
		if (!errors.mobile) {
			await http.get(`/sms/codes/${loginInfo.mobile}`).then(() => {
				setCodeText('已发送')
			}, () => {
				message.error('请求过于频繁，请稍后再试')
			})
		}
	}

	return (
		<form className="container" onSubmit={handleSubmit}>
			<div className="loginBox">
				<h1 className="title">极客园</h1>
				<div className="inputContainer">
					<input type="text" name="mobile" placeholder="请输入手机号" value={loginInfo.mobile} onChange={handleInputChange} />
				</div>
				{errors.mobile && <p className="error">{errors.mobile}</p>}
				<div className="codeContainer">
					<input type="text" name='code' placeholder="请输入验证码" value={loginInfo.code} onChange={handleInputChange} />
					<button type="button" className="codeBtn" onClick={handlerGetCode}>{codeText}</button>
				</div>
				{errors.code && <p className="error">{errors.code}</p>}
				<button className="loginBtn" type="submit" >登录</button>
			</div>
		</form>
	)
}

export default Login